﻿using OMG.Fill.Vegetable.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace OMG.Fill.Vegetables.UI
{
    public class AppUser
    {
        private static UserInfo user;
        private static object _object = new object();
        public static UserInfo GetUser()
        {
            if (HttpContext.Current.Request[FormsAuthentication.FormsCookieName] != null)
            {
                //先判断实例是否存在，不存在再加锁处理
                string userId ="";
                userId = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                UserServices users = new UserServices();
                //在同一时刻加了锁的那部分程序只有一个线程可以进入，
                lock (_object)
                {
                    if (user == null)
                    {
                        //如实例不存在，则null，否则返回已有实例
                        if (user == null)
                        {
                            var model = users.GetModel(userId).model;
                            user = new UserInfo { Account = model.Account, UserId = model.Id, UserName = model.UserName, UserType = model.UserType,LastLoginTime=model.LastLoginTime,AreaCode=model.AreaCode };
                        }
                    }
                    else
                    {
                        if (user.UserId != userId)
                        {
                            var model = users.GetModel(userId).model;
                            user = new UserInfo { Account = model.Account, UserId = model.Id, UserName = model.UserName, UserType = model.UserType, LastLoginTime = model.LastLoginTime, AreaCode = model.AreaCode };
                        }
                    }
                }
            }
            else
            {
                user = null;
            }
            return user;
        }
    }
    /// <summary>
    /// 根据需要扩展内容
    /// </summary>
    public class UserInfo
    {
        public string Account { get; set; }
        public string AreaCode { get; set; }
        public string UserId { get; set; }
        public string UserName { get; set; }
        /// <summary>
        /// 用户类型：0：超级管理员
        /// </summary>
        public string UserType { get; set; }
        public DateTime? LastLoginTime{ get; set; }
    }
}